package com.junqi.msg.event.listener;

import cn.hutool.core.collection.CollUtil;
import com.junqi.common.entity.Message;
import com.junqi.common.entity.RedisKeyManager;
import com.junqi.msg.adapter.WSAdapter;
import com.junqi.msg.event.UserPullMsgEvent;
import com.junqi.msg.service.WebSocketService;
import com.junqi.msg.utils.JsonUtils;
import com.junqi.msg.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户拉取新消息事件监听
 */
@Component
public class UserPullMsgListener {

    @Autowired
    private WebSocketService webSocketService;
    @Autowired
    WSAdapter wsAdapter;

    @Async
    @EventListener(classes = UserPullMsgEvent.class)
    public void pushMsg(UserPullMsgEvent event) {
        Long lastMsgTime = event.getLastMsgTime();//最新消息时间
        String roomId = event.getRoomId();//房间id
        String userId = event.getUserId();//用户
        Set<Message> messagesList=new HashSet<>();
        //如果最新消息时间=0，就是新登录的用户，按“消息优先级”从大到小最多获取最新20条数据
        if(lastMsgTime==0){
            messagesList.addAll(RedisUtil.getTopFromZSet(RedisKeyManager.generateKey(RedisKeyManager.ROOM_MSG,roomId),15));
        }else{
            //根据最新消息时间开始获取一批数据，按”消息优先”级获取大到小的消息多50条
            messagesList.addAll(RedisUtil.zRangeByScore(RedisKeyManager.generateKey(RedisKeyManager.ROOM_MSG,roomId),Double.valueOf(lastMsgTime),45));
        }
        if(CollUtil.isNotEmpty(messagesList)){
            //推送给指定的用户
            webSocketService.sendMessageToUid(JsonUtils.toStr(wsAdapter.buildChatMsgResp(messagesList)),userId);
        }

        /**********************************  通知合并机制 下  通知成功，清除队列和更新用户拉取状态=不等于拉取中  *******************************/
        RedisUtil.hdel(RedisKeyManager.generateKey(RedisKeyManager.WS_NOTIF_QUEUE_USERS), userId);
    }

}
